{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "import os\n",
    "import pandas as pd\n",
    "\n",
    "\n",
    "stopwords = [line.strip() for line in open('D:\\\\dianpingdata\\\\stopwords-master\\\\哈工大停用词表.txt', 'r', encoding='utf-8').readlines()]\n",
    "addwords = [line.strip() for line in open('D:\\\\dianpingdata\\\\stopwords-master\\\\饭店用高频词表.txt', 'r', encoding='ANSI').readlines()]\n",
    "for i in addwords:    #加载自定义关键词\n",
    "    jieba.add_word(i)\n",
    "os.chdir(r'D:\\dianpingdata\\大牌档')\n",
    "name = '南京大牌档'\n",
    "file = open(name+'.txt',encoding=\"UTF-8\")\n",
    "file_context = file.read()\n",
    "\n",
    "def cnwordcut(text, model = 0): #输入文本和分词模式，输出列表分词信息,默认为精确模式\n",
    "    if model == 0:\n",
    "        word = jieba.lcut(text)   #精确模式\n",
    "    elif model == 1:\n",
    "        word = jieba.lcut_for_search(text)  #搜索模式\n",
    "    else:\n",
    "        print('输入分词信息有误')\n",
    "    return word\n",
    "\n",
    "def nostopword(li): #去除停用词表内关键词\n",
    "    nostopword = []\n",
    "    for chara in li:\n",
    "        if chara not in stopwords:\n",
    "            if chara != '\\t'and'\\n':\n",
    "                nostopword.append(chara)\n",
    "    return(nostopword)\n",
    "                \n",
    " \n",
    "#统计词频\n",
    "type = 0\n",
    "words = nostopword(cnwordcut(file_context, type))\n",
    "data = {}\n",
    "for i in words:\n",
    "    if len(i)<2:\n",
    "        continue\n",
    "    if i in data:\n",
    "        data[i]+=1\n",
    "    else:\n",
    "        data[i]=1\n",
    "\n",
    "data = sorted(data.items(),key = lambda x:x[1],reverse = True) #排序\n",
    "c = pd.DataFrame(data)\n",
    "\n",
    "if type == 0:\n",
    "    oname = name+'精确分词结果.xlsx'\n",
    "else:\n",
    "    oname = name+'搜索分词结果.xlsx'\n",
    "c.to_excel(oname, encoding='UTF-8', index = False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
